package cn.niu;

import cn.niu.ts.TsPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by niusibao on 2017/8/1 0001.
 */
public class Live {

    Logger logger;
    private String name;

    //总长度 帧数 1帧 64ms
    private long length = 0;
    //8帧 512ms 为1组
    private int groupSize = 8;
    //保存4组作m3u8
    private int size = 3;
    //4组中的起始位置
    private int start = 0;
    private byte[][] tsArray = new byte[size][];
    private byte[][] aacArray = new byte[size][];
    private ByteArrayOutputStream tempStream = new ByteArrayOutputStream();
//    private byte[][] resultArray = new byte[size][];

    private long sequence;

    TsPackage tsPackage = new TsPackage();

    List<byte[]> audioTsList = new ArrayList<>();


    public Live(String name) {
        this.name = name;
        sequence = 0;
        logger = LoggerFactory.getLogger("Live-" + name);
    }

    public long getSequence() {
        return sequence;
    }


    public void putStream(byte[] bytes) throws IOException {

        List<byte[]> list = tsPackage.getAudioTs(bytes, length * 64 * 90);
        tempStream.write(bytes);
        audioTsList.addAll(list);

        if (length % groupSize == 0) {

            int index = (start + size) % size;
            //一个ts文件
            tsArray[index] = TsPackage.getTs(audioTsList);
            //一个aac文件
            aacArray[index] = tempStream.toByteArray();
            //清空数据
            tempStream.reset();
            audioTsList.clear();

            start = (start + 1) % size;
            sequence++;
        }

        length++;
    }

    public byte[] getBytes(long id, boolean isAAC) {
        id = start + id - sequence;
        if (id < 0) {
            id = start;
        }

        byte[] bytes;
        if (isAAC) {
            bytes = aacArray[(int) (id % size)];
        } else {
            bytes = tsArray[(int) (id % size)];
        }

        if (bytes == null) {
            bytes = new byte[1024];
        }
        return bytes;
    }
}
